//app.js
let mydevice;


/* CRC 高位字节值表 */ 
const auchCRCHi = [ 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 
  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
  0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 
  0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 
  0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 
  0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 
  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 
  0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 
  0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 
  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 
  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 
  0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 
  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
  0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 
  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 
  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 
  0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 
  0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 
  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 
];

const auchCRCLo = [ 
  0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 
  0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 
  0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 
  0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 
  0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4, 
  0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, 
  0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 
  0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 
  0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 
  0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 
  0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 
  0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, 
  0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 
  0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 
  0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 
  0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 
  0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 
  0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, 
  0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 
  0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 
  0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 
  0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 
  0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 
  0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, 
  0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 
  0x43, 0x83, 0x41, 0x81, 0x80, 0x40 
];



App({
  data:{
     BLE_Rebuff:new Uint8Array(256),//定义一个蓝牙接收数据缓存数组
     Rebuffi:0,//蓝牙接收数据数组下标
     BLE_Txbuff: new Uint8Array(20),//定义一个蓝牙接发送数据缓存数组
     BLE_Txbuff1: new Uint8Array(20),//定义一个蓝牙接发送数据缓存数组
     Txbuffid:0,//选择发送的buff,BLE_Txbuff or BLE_Txbuff1
     sendReq:0,//蓝牙发送请求标志
     mscount:0,//计时器
     crcerrcnt:0,//CRC计数值
     savereq:false,//参数存储请求
     mydevices:[],//蓝牙设备列表
     bleopen:false,//蓝牙打开标志
     connected: false,//蓝牙是否已连接标志
     blefound:false,//蓝牙已经找到标志
     blesendfailcnt:0,//数据发送失败次数
     blesendbusy:false,//蓝牙正在发送
     learninitreq:0,//显示更新请求
     advaninitreq:0,//显示更新请求
     expertinitreq:0,//显示更新请求
     connecttips:'',
     devicenameid:'',
     ptype:'',//控制器型号名
     mcuswver:'',//控制器软件版本号

     LOGOK:false//用户密码登录，OK
     
    },
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    this.adapterStateChangeHandler = null; // 保存监听器引用，用于移除
  },
  onLoad: function () {
    // 设置当前页面保持屏幕常亮
    wx.setKeepScreenOn({keepScreenOn: true});

  },
  onUnload: function () {
    // 恢复系统自动熄屏的设置
    wx.setKeepScreenOn({keepScreenOn: false});
    this.closeBLEConnection();
  },

  //================================================================

  crc16(data, length) { 
    let uchCRCHi = 0xFF; // 高CRC字节初始化
    let uchCRCLo = 0xFF; // 低CRC字节初始化
    for (let i = 0; i < length; i++) { // 遍历传输消息缓冲区
      let uIndex = uchCRCHi ^ data[i]; // 计算CRC
      uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex];
      uchCRCLo = auchCRCLo[uIndex];
    }
    return (uchCRCHi << 8 | uchCRCLo);
  },

  //断开蓝牙连接
  closeBLEConnection() {
      if(this.data.connected){
      wx.closeBLEConnection({
        deviceId: mydevice.deviceId
      })
     this.data.connected= false
    }
    // 断开连接时，清理状态
    this.data.blefound = false
    this.data.bleopen = false
    // 移除适配器状态监听器
    if (this.adapterStateChangeHandler) {
      wx.offBluetoothAdapterStateChange(this.adapterStateChangeHandler)
      this.adapterStateChangeHandler = null
      console.log('断开连接，已移除蓝牙适配器状态监听器')
    }
  },

//======================================================================
openBluetoothAdapter() {
  
  this.data.connecttips='控制器搜索中...'
  wx.openBluetoothAdapter({
    success: (res) => {
      console.log('openBluetoothAdapter success')
      this.startBluetoothDevicesDiscovery()
    },
    fail: (res) => {
      this.data.connecttips='请打开手机蓝牙' 
      // 在失败后延迟3秒后再次尝试打开蓝牙适配器
        setTimeout(() => {
          this.openBluetoothAdapter();
      }, 3000); // 3000毫秒等于3秒
      if (res.errCode === 10001) {
        // 避免重复注册监听器
        if (!this.adapterStateChangeHandler) {
          this.adapterStateChangeHandler = (res) => {
            console.log('onBluetoothAdapterStateChange', res)
            // 只在蓝牙可用且不在搜索中时才启动搜索
            if (res.available && !res.discovering && !this.data.blefound) {
              console.log('蓝牙适配器已就绪，开始搜索设备')
              this.startBluetoothDevicesDiscovery()
            }
          }
          wx.onBluetoothAdapterStateChange(this.adapterStateChangeHandler)
        }
      }
    }
  })
},
getBluetoothAdapterState() {
  wx.getBluetoothAdapterState({
    success: (res) => {
      console.log('getBluetoothAdapterState', res)
      if (res.discovering) {
        this.onBluetoothDeviceFound()
      } else if (res.available) {
        this.startBluetoothDevicesDiscovery()
      }
    }
  })
},
startBluetoothDevicesDiscovery() {
  wx.startBluetoothDevicesDiscovery({
    allowDuplicatesKey: true,
    success: (res) => {
      console.log('startBluetoothDevicesDiscovery success')
      this.onBluetoothDeviceFound()
    },
  })
},
stopBluetoothDevicesDiscovery() {
  wx.stopBluetoothDevicesDiscovery()
},

/**找到新蓝牙设备的监听 */
onBluetoothDeviceFound() {
  wx.onBluetoothDeviceFound((res) => {
    res.devices.forEach(device => {
      if (!device.name && !device.localName ) {
        return 
      }
      if((!device.name.startsWith('DUNEN'))&&(!device.name.startsWith('HC'))&&(!device.name.startsWith('Dunen'))){//DUNEN开头
        return 
      }
      this.data.connecttips='已找到'
      //this.appendLog('已找到'+device.name + device.deviceId+'\n');
      mydevice = device;
      this.data.blefound = true;
      
      // 找到目标设备后，停止搜索并移除适配器状态监听器
      console.log('已找到目标设备，停止搜索')
      this.stopBluetoothDevicesDiscovery()
      if (this.adapterStateChangeHandler) {
        wx.offBluetoothAdapterStateChange(this.adapterStateChangeHandler)
        this.adapterStateChangeHandler = null
        console.log('已移除蓝牙适配器状态监听器')
      }
    })
  })
},

//=================================================================================
createBLEConnection() {//连接搜索到的蓝牙设备

  this.data.connecttips='正连接...'
  //this.appendLog('正连接...\n');

  this.data.learnreq = 1;//页面更新请求
  this.data.advaninitreq =1;//页面更新请求
  this.data.expertinitreq =1;//页面更新请求


  const deviceId = mydevice.deviceId;

   this.data.devicenameid = mydevice.deviceId//给app,显示用

  wx.createBLEConnection({
    deviceId,
    success: (res) => {

      this.getBLEDeviceServices(deviceId)//获取蓝牙设备的服务

    }
  })
  this.stopBluetoothDevicesDiscovery()//蓝牙设备成功连接上后，自动关闭蓝牙设备的搜寻 c.xie

},

//获取蓝牙服务
getBLEDeviceServices(deviceId) {
  wx.getBLEDeviceServices({
    deviceId,
    success: (res) => {
      for (let i = 0; i < res.services.length; i++) {
        if (res.services[i].isPrimary) {
          this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
        //  this.appendLog('蓝牙服务已获取成功\n');
          this.data.connected= true,//蓝牙连接成功
          this.data.connecttips='控制器连接成功！tips:双击曲线重绘'
       //   this.appendLog('已连接到'+mydevice.name + mydevice.deviceId+'\n');
          
          // 连接成功后，确保移除适配器状态监听器
          if (this.adapterStateChangeHandler) {
            wx.offBluetoothAdapterStateChange(this.adapterStateChangeHandler)
            this.adapterStateChangeHandler = null
            console.log('连接成功，已移除蓝牙适配器状态监听器')
          }

          return
        }
      }
    }
  })
},

getBLEDeviceCharacteristics(deviceId, serviceId) {
  let that = this;
  wx.getBLEDeviceCharacteristics({
    deviceId,
    serviceId,
    success: (res) => {
    //  console.log('\ngetBLEDeviceCharacteristics success', res.characteristics)//这里面含有蓝牙的接收返回数据
    console.log('\ngetBLEDeviceCharacteristics success')
      for (let i = 0; i < res.characteristics.length; i++) {
        let item = res.characteristics[i]
        if (item.properties.read) {
          wx.readBLECharacteristicValue({
            deviceId,
            serviceId,
            characteristicId: item.uuid,
          })
        }
        if (item.properties.write) {
          this._deviceId = deviceId
          this._serviceId = serviceId
          this._characteristicId = item.uuid
          //this.writeBLECharacteristicValue()
        }
        if (item.properties.notify || item.properties.indicate) {
          wx.notifyBLECharacteristicValueChange({
            deviceId,
            serviceId,
            characteristicId: item.uuid,
            state: true,
          })
        }
      }
    },
    fail(res) {
      console.error('getBLEDeviceCharacteristics', res)
    }
  })
  wx.onBLEConnectionStateChange((res) => {
    console.log(`蓝牙连接状态变化：`, res);
    if (!res.connected) {
      // 如果连接断开，尝试重新连接
     // reconnectToDevice();
     if(that.data.connected==false)
     {
       wx.showToast({
         title: '蓝牙正在重新连接',
         icon: 'none', // 提示框的图标，可选值：'success', 'loading', 'none'（默认值）
         duration: 2000, // 提示框显示时间（毫秒），默认值为 1500
         mask: true // 是否显示透明蒙层，避免触摸穿透，可选值：true，false（默认值）
       })
     }
    that.data.connected=false

    }
  });
  // 操作之前先监听，保证第一时间获取数据
  wx.onBLECharacteristicValueChange((characteristic) => {
    const array = new Uint8Array(characteristic.value);//const 变量只能定义赋值一次。
   
    for (var i = 0; i < array.length; i++){
      that.data.BLE_Rebuff[that.data.Rebuffi++] =array[i]; 

      if(that.data.Rebuffi>255){
        that.data.Rebuffi = 255;
      }
      that.data.mscount= 0;//清零接收间隔时间
    }
  })
},
  //向蓝牙设备发送
  writeBLECharacteristicValue() {
    let that = this;
   // that.appendLog('数据发送...')

    let buffer = new ArrayBuffer(8)
    let view = new Uint8Array(buffer);
    for(var i=0;i<8;i++)
    {
      view[i] = that.data.BLE_Txbuff[i];
    }

    let buffer1 = new ArrayBuffer(13)
    let view1 = new Uint8Array(buffer1);
    for(var i=0;i<13;i++)
    {
      view1[i] = that.data.BLE_Txbuff1[i];
    }
    that.data.Rebuffi = 0//接收缓存数据下标清零。
    that.data.blesendfailcnt =1;
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: that.data.Txbuffid==0? buffer:buffer1,
      success: (res) => {
        console.log('Send OK!')
      //  that.appendLog('数据发送成功')
        that.data.blesendfailcnt =0
      },
      fail: (err) => {
        console.error('\n蓝牙发送数据失败...请尝试重启控制器钥匙电源，关闭并打开小程序重新操作')
     //   that.appendLog('数据发送失败')
        if(that.data.blesendfailcnt++>10)//连续10次发送失败
        {
        }

      }
    })
  },

  //向蓝牙设备发送
  writeBLECharacteristicValue() {
    let that = this;
   // that.appendLog('数据发送...')

    let buffer = new ArrayBuffer(8)
    let view = new Uint8Array(buffer);
    for(var i=0;i<8;i++)
    {
      view[i] = that.data.BLE_Txbuff[i];
    }

    let buffer1 = new ArrayBuffer(13)
    let view1 = new Uint8Array(buffer1);
    for(var i=0;i<13;i++)
    {
      view1[i] = that.data.BLE_Txbuff1[i];
    }
    that.data.Rebuffi = 0//接收缓存数据下标清零。
    that.data.BLE_Rebuff[0] = 0;//首个字节也清零
    that.data.BLE_Rebuff[1] = 0;//第二字节也清零
    that.data.BLE_Rebuff[2] = 0;//清零
    that.data.BLE_Rebuff[3] = 0;//清零
    that.data.blesendfailcnt = 1;

    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: that.data.Txbuffid==0? buffer:buffer1,
      success: (res) => {
        console.log('Send OK!')
      //  that.appendLog('数据发送成功')
        that.data.blesendfailcnt =0
      },
      fail: (err) => {
        console.error('\n蓝牙发送数据失败...请尝试重启控制器钥匙电源，关闭并打开小程序重新操作')
     //   that.appendLog('数据发送失败')
        if(that.data.blesendfailcnt++>10)//连续10次发送失败
        {
        }

      }
    })
  },

    //向蓝牙设备发送
    writeBLECharacteristicValuebin() {
      let that = this;
     // that.appendLog('数据发送...')
  
      let buffer = new ArrayBuffer(16)
      let view = new Uint8Array(buffer);
      for(var i=0;i<16;i++)
      {
        view[i] = that.data.BLE_Txbuff[i];
      }
  
      let buffer1 = new ArrayBuffer(5)
      let view1 = new Uint8Array(buffer1);
      for(var i=0;i<5;i++)
      {
        view1[i] = that.data.BLE_Txbuff1[i];
      }

      that.data.Rebuffi = 0//接收缓存数据下标清零。
      that.data.BLE_Rebuff[0] = 0;//首个字节也清零
      that.data.BLE_Rebuff[1] = 0;//第二字节也清零
      that.data.blesendfailcnt = 1;

      
      wx.writeBLECharacteristicValue({
        deviceId: this._deviceId,
        serviceId: this._serviceId,
        characteristicId: this._characteristicId,
        value: that.data.Txbuffid==0? buffer:buffer1,
        success: (res) => {
          console.log('Send OK!')
        //  that.appendLog('数据发送成功')
          that.data.blesendfailcnt =0
        },
        fail: (err) => {
          console.error('\n蓝牙发送数据失败...请尝试重启控制器钥匙电源，关闭并打开小程序重新操作')
       //   that.appendLog('数据发送失败')
          if(that.data.blesendfailcnt++>10)//连续10次发送失败
          {
          }
  
        }
      })
    },
     //向蓝牙设备发送
     writeBLECharacteristicValue2boot() {
      let that = this;
     // that.appendLog('数据发送...')
  
      let buffer = new ArrayBuffer(1)
      let view = new Uint8Array(buffer);
      for(var i=0;i<1;i++)
      {
        view[i] = that.data.BLE_Txbuff[i];
      }
  
      let buffer1 = new ArrayBuffer(5)
      let view1 = new Uint8Array(buffer1);
      for(var i=0;i<5;i++)
      {
        view1[i] = that.data.BLE_Txbuff1[i];
      }

      that.data.Rebuffi = 0//接收缓存数据下标清零。
      that.data.BLE_Rebuff[0] = 0;//首个字节也清零
      that.data.BLE_Rebuff[1] = 0;//第二个字节也清零
      that.data.BLE_Rebuff[2] = 0;//第三个字节也清零
      that.data.blesendfailcnt = 1;
      wx.writeBLECharacteristicValue({
        deviceId: this._deviceId,
        serviceId: this._serviceId,
        characteristicId: this._characteristicId,
        value: that.data.Txbuffid==0? buffer:buffer1,
        success: (res) => {
          console.log('Send OK!')
        //  that.appendLog('数据发送成功')
          that.data.blesendfailcnt =0
        },
        fail: (err) => {
          console.error('\n蓝牙发送数据失败...请尝试重启控制器钥匙电源，关闭并打开小程序重新操作')
       //   that.appendLog('数据发送失败')
          if(that.data.blesendfailcnt++>10)//连续10次发送失败
          {
          }
  
        }
      })
    }
  
})